<style lang="less" scoped>
  @import './databook.less';
</style>

<template>
  <div class="layout">
    <Layout :style="{height: '100%'}">
        <Sider
          :style="{height: '100%', left: 0, overflow: 'auto', background: '#FFFFFF'}"
          :width="260"
          :collapsed-width="64"
          hide-trigger>
            <Row :gutter="4">
              <Col span="20">
                <Select class="workspace-select" v-model="workspaceName"
                  placeholder="请选择数据空间" clearable filterable
                  @on-change="workspaceSelectChangeHandle">
                    <Option
                      v-for="item in workspaceList"
                      :value="item"
                      :key="item">{{ item }}</Option>
                </Select>
              </Col>
              <Col span="4">
                <Tooltip content="管理数据空间" placement="bottom-end">
                  <Button class="workspace-manage-btn"
                    @click="isWorkspaceManageShow = true"><Icon type="md-settings"></Icon></Button>
                </Tooltip>
              </Col>
            </Row>

            <Row :gutter="4" v-show="!this.workspaceName == false">
              <Col span="20">
                <Input v-model="newBookshelf.name" placeholder="请输入书架名"/>
              </Col>
              <Col span="4">
                <Tooltip content="添加书架" placement="bottom-end">
                  <Button class="workspace-manage-btn" @click="addBookshelfClickHandle"><Icon type="md-add"></Icon></Button>
                </Tooltip>
              </Col>
            </Row>

            <Menu @on-open-change="bookshelfMenuOpenChangeHandle" @on-select="bookshelfMenuSelectHandle" :accordion="true">
                <Submenu v-for="(list, item) in bookshelfList" :name="item" :key="item">
                    <template slot="title">
                      {{item}}
                      <Button @click.stop="addDatabookClickHandle(item)" style="float: right;" size="small" type="success" ghost>添加数据本</Button>
                      <Button @click.stop="deleteBookshelfClickHandle(item)" style="float: right;" size="small" type="error" ghost>删除</Button>
                    </template>
                    <MenuItem v-for="databook in list" :key="item + '*' + databook" :name="item + '*' + databook">{{databook}}</MenuItem>
                </Submenu>
            </Menu>
        </Sider>
        <Content>
          <div class="content">
            <databook-editor :columns="selectDatabookData.columns" :data="selectDatabookData.data" @collectImage="collectImageHandle" />
            <Button type="success" style="width: 100%; margin: 4px 0px;" ghost @click="saveDatabookClickHandle">保存数据本</Button>
            <vue-json-editor v-model="selectDatabookData" :showBtns="false" :mode="'code'" lang="zh" />
          </div>
        </Content>
    </Layout>
    <Drawer title="数据空间管理" placement="left" width="460" :closable="false" v-model="isWorkspaceManageShow">
      <Row :gutter="4">
        <Col span="20">
          <Input v-model="newWorkspace.name" placeholder="请输入数据空间名"/>
        </Col>
        <Col span="4">
          <Tooltip content="添加数据空间" placement="bottom-end">
            <Button @click="addWorkspaceClickHandle"><Icon type="md-add"></Icon></Button>
          </Tooltip>
        </Col>
      </Row>
      <Alert v-show="newWorkspace.addErr" style="margin: 4px 0px;" type="error" show-icon>
        {{newWorkspace.addErrTips}}
      </Alert>

      <CellGroup>
        <Cell v-for="item in workspaceList" :key="item" :title="item">
            <Button slot="extra" type="error" size="small" @click="deleteWorkspaceClickHandle(item)">删除</Button>
        </Cell>
      </CellGroup>
    </Drawer>
  </div>
</template>

<script>
import DatabookEditor from '_c/databook-editor'
import vueJsonEditor from 'vue-json-editor'
import { listWorkspace, addWorkspace, deleteWorkspace } from '@/api/workspace'
import { listBookshelf, addBookshelf, deleteBookshelf } from '@/api/bookshelf'
import { listDatabook, addDatabook, infoDatabook, saveDatabook, collectImage } from '@/api/databook'
export default {
  components: {
    DatabookEditor,
    vueJsonEditor
  },
  data () {
    return {
      workspaceName: '',
      bookshelfName: '',
      databookName: '',
      workspaceList: [],
      isWorkspaceManageShow: false,
      newWorkspace: {
        name: '',
        addErr: false,
        addErrTips: ''
      },
      bookshelfList: {},
      newBookshelf: {
        name: ''
      },
      newDatabook: {
        name: ''
      },
      selectDatabookData: {
        columns: [],
        data: []
      }
    }
  },
  mounted () {
  },
  activated () {
    this.init()
  },
  deactivated () {
  },
  methods: {
    init () {
      this.loadWorkspaces()
    },
    loadWorkspaces () {
      listWorkspace().then(res => {
        this.workspaceList = res
      })
    },
    loadBookshelf () {
      if (this.workspaceName) {
        listBookshelf(this.workspaceName).then(res => {
          this.bookshelfList = {}
          for (let key in res) {
            // this.bookshelfList[res[key]] = []
            this.$set(this.bookshelfList, res[key], [])
          }
        })
      } else {
        this.bookshelfList = {}
      }
    },
    loadDatabook (bname) {
      if (this.workspaceName) {
        listDatabook(this.workspaceName, bname).then(res => {
          // this.bookshelfList[bname] = res
          this.$set(this.bookshelfList, bname, res)
        })
      }
    },
    addWorkspaceClickHandle () {
      if (!this.newWorkspace.name) {
        this._showAddWorkspaceErr('数据空间名不能为空')
        return
      }
      this._closeAddWorkspaceErr()

      addWorkspace(this.newWorkspace.name).then(res => {
        if (this.newWorkspace.name !== res) {
          this._showAddWorkspaceErr(res)
          return
        }
        this._closeAddWorkspaceErr()
        this.loadWorkspaces()
      })
    },
    deleteWorkspaceClickHandle (wname) {
      if (wname) {
        deleteWorkspace(wname).then(res => {
          if (wname !== res) {
            this._showAddWorkspaceErr(res)
            return
          }
          this._closeAddWorkspaceErr()
          this.loadWorkspaces()
        })
      }
    },
    workspaceSelectChangeHandle (value) {
      this.loadBookshelf()
    },
    addBookshelfClickHandle () {
      if (!this.newBookshelf.name) {
        this.$Message.error('书架名不能为空')
        return
      }

      addBookshelf(this.workspaceName, this.newBookshelf.name).then(res => {
        if (this.newBookshelf.name !== res) {
          this.$Message.error(res)
          return
        }
        this.loadBookshelf()
      })
    },
    deleteBookshelfClickHandle (name) {
      if (name) {
        deleteBookshelf(this.workspaceName, name).then(res => {
          if (name !== res) {
            this.$Message.error(res)
            return
          }
          this.loadBookshelf()
        })
      }
    },
    bookshelfMenuOpenChangeHandle (arr) {
      for (let key in arr) {
        this.loadDatabook(arr[key])
      }
    },
    bookshelfMenuSelectHandle (value) {
      let arr = value.split('*')

      this.bookshelfName = arr[0]
      this.databookName = arr[1]

      infoDatabook(this.workspaceName, this.bookshelfName, this.databookName).then(res => {
        this.selectDatabookData = {
          columns: [],
          data: []
        }
        if (Object.prototype.toString.call(res) === '[object Object]') {
          for (let key in res) {
            let value = res[key]
            this.$set(this.selectDatabookData, key, value)
          }
        }
      })
    },
    addDatabookClickHandle (bname) {
      let _this = this
      this.$Modal.confirm({
        title: '在书架[' + bname + ']下添加数据本',
        okText: '确认添加',
        cancelText: '取消',
        onOk () {
          if (!_this.newDatabook.name) {
            this.$Message.error('数据本名称不能为空')
            return
          }

          addDatabook(_this.workspaceName, bname, _this.newDatabook.name).then(res => {
            if (_this.newDatabook.name !== res) {
              this.$Message.error(res)
              return
            }
            _this.loadDatabook(bname)
          })
        },
        render: (h) => {
          return h('Input', {
            props: {
              value: _this.newDatabook.name,
              autofocus: true,
              placeholder: '请输入数据本名称'
            },
            on: {
              input: (val) => {
                _this.newDatabook.name = val
              }
            }
          })
        }
      })
    },
    collectImageHandle (columnKey) {
      collectImage(this.workspaceName, this.bookshelfName, this.databookName, columnKey).then(res => {
        if (columnKey === res) {
          this.$Message.success('开始采集图片...')
        } else {
          this.$Message.error(res)
        }
      })
    },
    saveDatabookClickHandle () {
      if (!this.workspaceName) {
        this.$Message.error('请先选择数据空间')
        return
      }
      if (!this.bookshelfName) {
        this.$Message.error('请先选择书架')
        return
      }
      if (!this.databookName) {
        this.$Message.error('请先选择数据本')
        return
      }

      saveDatabook(this.workspaceName, this.bookshelfName, this.databookName, this.selectDatabookData).then(res => {
        if (this.databookName === res) {
          this.$Message.success('保存成功')
        } else {
          this.$Message.error(res)
        }
      })
    },
    _showAddWorkspaceErr (tips) {
      this.$set(this.newWorkspace, 'addErrTips', tips)
      this.$set(this.newWorkspace, 'addErr', true)
    },
    _closeAddWorkspaceErr () {
      this.$set(this.newWorkspace, 'addErr', false)
    }
  }
}
</script>

<style>

</style>
